package com.smartthinking.destinomusical.camara;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;

public class CameraPreview extends SurfaceView implements
		SurfaceHolder.Callback {
	SurfaceHolder holder,mediaHolder;
	Camera camera;
	private int lastReportedWidth;
	private int lastReportedHeight;
	private int cameraId;
	private static final String TAG = "CameraPreviewLog";
	private CameraPreviewProvider previewProvider;

	public MediaRecorder mrec = new MediaRecorder();
	
	public CameraPreview(Context context, AttributeSet attrs, int cameraId) {
		super(context, attrs);
		this.cameraId = cameraId;
		Log.d(TAG, "Constructing CameraPreview");
		setUpHolder();
		
	}
	
	public void setUpHolder(){
		holder = getHolder();
		holder.addCallback(this);
		holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		mediaHolder=holder;
		restartPreview(cameraId);
	}
	
	public void restartPreview(int cameraId){
		this.cameraId = cameraId;
		previewProvider = null;
		// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
		previewProvider = new CameraPreviewGingerbread();
		// } else {
		// previewProvider = new CameraPreviewFroyo();
		// }
	}

	public void surfaceCreated(SurfaceHolder holder) {
		Log.d(TAG, "SurfaceCreated");
		preparePreview();
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		// Surface will be destroyed when we return, so stop the preview.
		// Because the CameraDevice object is not a shared resource, it's very
		// important to release it when the activity is paused.
		Log.d(TAG, "SurfaceDestroyed");
		stopPreview();
	}

	private void preparePreview() {
		Log.d(TAG, "preparePreview");
		// The Surface has been created, acquire the camera and tell it where
		// to draw.
		try {
			camera = previewProvider.openCamera(cameraId);
			camera.setPreviewDisplay(holder);
		} catch (Exception exception) {
			if (camera != null) {
				camera.release();
			}
			camera = null;
		}
	}

	private void stopPreview() {
		Log.d(TAG, "stopPreview");
		if (camera != null) {
			camera.stopPreview();
			camera.release();
			camera = null;
		}
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
		Log.d(TAG, "SurfaceChanged");
		this.lastReportedWidth = w;
		this.lastReportedHeight = h;
		if (camera != null) {
			startPreview();
		}
	}

	private void startPreview() {
		Log.d(TAG, "startPreview");
		// Now that the size is known, set up the camera parameters and begin
		// the preview.
		Display display = ((WindowManager) getContext().getSystemService(
				Context.WINDOW_SERVICE)).getDefaultDisplay();
		previewProvider.startPreview(camera, lastReportedWidth,
				lastReportedHeight, display);
	}

	public  boolean startRecording() {
		camera.stopPreview();
		try {
			if (camera == null) {
				preparePreview();
			}
				String filename;
				String path;

				path = Environment.getExternalStorageDirectory()
						.getAbsolutePath().toString()+"/DestinoMusical/";

				Date date = new Date();
				filename = "camPrev"
					+ date.toString().replace(" ", "_").replace(":", "_")
					+ ".mp4";
				File parentDirectory = new File(path);
				if(!parentDirectory.exists())
				{
				    System.err.println("It seems like parent directory does not exist...");
				    if(!parentDirectory.mkdirs())
				    {
				         System.err.println("And we cannot create it...");
				         // we have to return, throw or something else
				    }
				}
				
				mrec = new MediaRecorder();

				camera.lock();
				camera.unlock();

				mrec.setCamera(camera);
				mrec.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
				mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
				mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
				mrec.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
				mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
				mrec.setPreviewDisplay(mediaHolder.getSurface());
				mrec.setOutputFile(path + filename);
				//mrec.setOrientationHint(90);
				mrec.prepare();
				mrec.start();
			
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	public boolean stopRecording() {
		try {
			if (mrec != null) {
				mrec.stop();
				mrec.reset();
				mrec.release();
				mrec = null;

			}
			camera.reconnect();
			camera.startPreview();
//			restartPreview(cameraId);
//			startPreview();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
		
		
	}

}
